package cn.wolfcode.crm.web.controller;

import cn.wolfcode.crm.domain.Department;
import cn.wolfcode.crm.query.QueryObject;
import cn.wolfcode.crm.service.IDepartmentService;
import cn.wolfcode.crm.util.JsonResult;
import cn.wolfcode.crm.util.PageResult;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
@RequestMapping("department")
public class DepartmentController {

    @Autowired
    IDepartmentService departmentService;

    @RequestMapping("view")
    @RequiresPermissions(value = {"department:view","部门页面"},logical = Logical.OR)
    public String view() {
        return "department";
    }

    @RequestMapping("query")
    @ResponseBody
    @RequiresPermissions(value = {"department:query","部门列表"},logical = Logical.OR)
    public PageResult query(QueryObject qo) {
        return departmentService.query(qo);
    }

    @RequestMapping("selectAll")
    @ResponseBody
    public List<Department> selectAll() {
        return departmentService.selectAll();
    }

    @RequestMapping("validateName")
    @ResponseBody
    public boolean validateUsername(String name, Long id) {
        Department dept = departmentService.getByName(name);
        //通过传回的用户名，如果查出来为null，则代表这个名字可以使用为true
        //如果查出来有值，且和传回的编辑的id相同，则相当于为同一个员工对象，允许保存，通过验证
        return dept == null || dept.getId() == id;
    }

    @RequestMapping("changeState")
    @ResponseBody
    @RequiresPermissions(value = {"department:changeState","部门停用"},logical = Logical.OR)
    public JsonResult changeState(Long id) {
        try {
            departmentService.changeState(id);
            return JsonResult.success("");
        } catch (Exception e) {
            e.printStackTrace();
            return JsonResult.mark("操作失败");
        }
    }

    @RequestMapping("saveOrUpdate")
    @ResponseBody
    @RequiresPermissions(value = {"department:saveOrUpdate","部门新增/更改"},logical = Logical.OR)
    public JsonResult saveOrUpdate(Department dept) {
        try {
            if (dept.getId() != null) {
                departmentService.updateByPrimaryKey(dept);
            } else {
                //保存新的员工要设置默认的状态为在职
                departmentService.insert(dept);
            }
            return JsonResult.success("");
        } catch (Exception e) {
            e.printStackTrace();
            return JsonResult.mark("保存失败");
        }
    }
}
